package vip.xumy.admin.sys.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.log4j.Log4j2;
import vip.xumy.admin.utils.LoginUtil;
import vip.xumy.core.exception.CoreException;
import vip.xumy.core.golbal.GlobalBuffer;
import vip.xumy.core.pojo.BufferResult;
import vip.xumy.core.pojo.com.AjaxResponse;
import vip.xumy.core.pojo.com.Cache;

/**
 * @author:mengyxu
 * @date:2019年12月13日
 */

@Log4j2
@RestController
@RequestMapping("memory")
public class MemoryController {

	@RequestMapping("buffer/list")
	public List<BufferResult> getBufferList(HttpServletRequest request) {
		log.info("查询缓存列表，当前登陆用户：" + LoginUtil.getUserId(request));
		List<BufferResult> list = new ArrayList<>();
		Map<String, Cache> buffer = GlobalBuffer.getBuffer();
		for (String key : buffer.keySet()) {
			list.add(new BufferResult(key, buffer.get(key)));
		}
		return list;
	}

	@RequestMapping("buffer/clean")
	public AjaxResponse cleanBuffer(HttpServletRequest request) {
		log.info("清空失效缓存，当前登陆用户：" + LoginUtil.getUserId(request));
		GlobalBuffer.cleanCache();
		return new AjaxResponse(true, "清空失效缓存成功");
	}

	@RequestMapping(value = "buffer/delete", method = RequestMethod.POST)
	public AjaxResponse deleteBuffer(@RequestBody BufferResult buffer, HttpServletRequest request) {
		String key = buffer.getKey();
		log.info("删除缓存：" + key + "，当前登陆用户：" + LoginUtil.getUserId(request));
		GlobalBuffer.removeCache(key);
		return new AjaxResponse(true, "删除缓存成功");
	}

	@RequestMapping(value = "buffer/delay", method = RequestMethod.POST)
	public AjaxResponse delayBuffer(@RequestBody BufferResult buffer, HttpServletRequest request) throws CoreException {
		log.info("修改缓存失效时间：" + buffer.getKey() + "，当前登陆用户：" + LoginUtil.getUserId(request));
		GlobalBuffer.setLoseTime(buffer.getKey(), buffer.getLoseTime());
		return new AjaxResponse(true, "修改缓存失效时间成功");
	}

}
